package com.cmlite;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.cmlite.base.BaseActivity;
import com.cmlite.component.ClearableEditText;
import com.cmlite.connect.AsyncTask_Api;
import com.cmlite.connect.AsyncTask_ApiListener;
import com.cmlite.connect.CallApi;
import com.cmlite.connect.ScreenStopper;
import com.cmlite.model.OutLogin;
import com.cmlite.model.OutResult;
import com.cmlite.util.ConnectionException;
import com.cmlite.util.EmptyDataException;
import com.cmlite.util.SecurityUtils;
import com.cmlite.util.SharedPreferencesDB;
import com.cmlite.util.TokenUnableException;
import com.cmlite.util.Util;

public class A1002Login extends BaseActivity implements OnClickListener,
		AsyncTask_ApiListener {

	private Button btn_login, btn_register;
	private ClearableEditText et_username, et_password, et_org;
	private int type = 0;
	private TextView tv_org, tv_usename, tv_password;
	private String key_md5;
	private String key_iv;
	private List<String> array;
	private Context mContext;
	private OutLogin mOutLogin;
	private static final int DIALOG_NUMBER = 0;
	private static final int TYPE_LOGIN = 0;
	private static final int TYPE_UPDATE = 1;
	private String username, password, org;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		openDatabase();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void initView() {
		setContentView(R.layout.a002login);

		this.mContext = this;
		btn_register = (Button) this.findViewById(R.id.login_bt_register);
		btn_login = (Button) this.findViewById(R.id.login_bt_login);

		et_org = (ClearableEditText) this.findViewById(R.id.login_ed_org);
		et_username = (ClearableEditText) this
				.findViewById(R.id.login_ed_username);
		et_password = (ClearableEditText) this.findViewById(R.id.login_ed_pass);
		tv_org = (TextView) this.findViewById(R.id.login_org);
		tv_usename = (TextView) this.findViewById(R.id.login_tv_username);
		tv_password = (TextView) this.findViewById(R.id.login_tv_pass);

//		et_org.setText("ajtom");
//		et_username.setText("ajtom24@outlook.com");
//		et_password.setText("123123");

		this.btn_login.setOnClickListener(this);
		this.btn_register.setOnClickListener(this);
		initData();
	}

	private void initData() {
		key_md5 = getResources().getString(R.string.md5_key);
		key_iv = getResources().getString(R.string.iv_key);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.login_bt_login:
			forceLogin();
			// Intent intent = new Intent(A1002Login.this, A003ListEvent.class);
			// startActivityForResult(intent, 1);
			break;
		case R.id.login_bt_register:
			forceRegister();
			break;
		default:
			break;
		}
	}

	private boolean isEmptyAll(String org, String email, String password) {
		if (TextUtils.isEmpty(org) || TextUtils.isEmpty(email)
				|| TextUtils.isEmpty(password))
			return true;
		return false;
	}

	private void forceLogin() {
		Log.d("A1002Login", "Perform Login...");
		Util.hideSoftKeyboard(mContext, et_username);
		String un_email, un_password, un_org;
		try {
			un_email = this.et_username.getText().toString().trim();
			un_password = this.et_password.getText().toString().trim();
			un_org = this.et_org.getText().toString().trim();
			if (!isEmptyAll(un_org, un_email, un_password)) {
				if (Util.isEmailValid(un_email)) {
					if (Util.getNetworkStatus(mContext)) {
						username = SecurityUtils.encrypt(un_email, key_iv,
								key_md5);
						password = SecurityUtils.encrypt(un_password, key_iv,
								key_md5);
						org = un_org;
						AsyncTask_Api apiTask = new AsyncTask_Api(this, this,
								TYPE_LOGIN, 0,
								ScreenStopper.STYLE_PROGRESS_PROCESS);
						apiTask.execute();
					} else {
						Util.showDialog(this, R.string.warning,
								"Network error !", R.drawable.exclamation);
					}
				} else {
					Util.showDialog(this, R.string.warning,
							mRes.getString(R.string.msg_error_incorret_gmail),
							R.drawable.exclamation);
				}
			} else {
				Util.showDialog(this, R.string.warning,
						R.string.msg_error_empty_infor, R.drawable.exclamation);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {

		}
	}

	@Override
	public Object callApi(int serachType, Object apidata) {
		if (serachType == TYPE_LOGIN) {
			OutLogin out = new OutLogin();
			try {
				out = CallApi.getLogin(this, username, password, org);
			} catch (EmptyDataException ex) {
				out.setCode(OutResult.CODE_ERROR_EMPTY);
				out.setMessage(getString(R.string.error_emptydata));
			} catch (TokenUnableException ex) {
				out.setCode(OutResult.CODE_TOKEN);
				out.setMessage(getString(R.string.error_token));
			} catch (ConnectionException ex) {
				out.setCode(OutResult.CODE_ERROR_CONNCECT);
				out.setMessage(getString(R.string.error_connection));
			} catch (Exception ex) {
				out.setCode(OutResult.CODE_ERROR_SYSTEM);
				out.setMessage(getString(R.string.error_system));
			}
			return out;
		}
		return null;
	}

	@Override
	public void finishApi(int serachType, Object apiresult) {
		if (serachType == TYPE_LOGIN) {
			mOutLogin = (OutLogin) apiresult;
			if (mOutLogin != null) {
				Log.e("A002Login", mOutLogin.toString());
				SharedPreferencesDB db = new SharedPreferencesDB(this);
				db.setPrefToken(mOutLogin.getToken());
				db.setPrefFirstStart(true);
				db.setPrefEmail(mOutLogin.getProfile().getEmail());

				if (mOutLogin.getStatus()) {
					Intent intent = new Intent(A1002Login.this,
							A003ListEvent.class);
					startActivity(intent);
					overridePendingTransition(0, android.R.anim.slide_out_right);
				}
				// Util.showDialog(
				// mContext,
				// R.string.update,
				// mContext.getResources().getString(R.string.msg_update_number_01)
				// + " " + mNumber + " " +
				// mContext.getResources().getString(R.string.msg_update_number_02),
				// R.string.ok, R.string.cancel,
				// new DialogInterface.OnClickListener() {
				//
				// @Override
				// public void onClick(DialogInterface dialog,
				// int which) {
				// // TODO Auto-generated method stub
				// getUpdateProfile();
				// }
				// }, new DialogInterface.OnClickListener() {
				//
				// @Override
				// public void onClick(DialogInterface dialog,
				// int which) {
				// // TODO Auto-generated method stub
				// if (!mDB.checkEmail(mOutLogin.getProfile()
				// .getEmail())) {
				// mDB.createProfile(mOutLogin
				// .getProfile());
				// } else {
				// mDB.updateProfile(mOutLogin
				// .getProfile());
				// }
				// Intent intent = new Intent(A1002Login.this,
				// A003ListEvent.class);
				// startActivityForResult(intent, 1);
				// }
				// });

				// Intent intent = new Intent(A1002Login.this,
				// A003ListEvent.class);
				// startActivityForResult(intent, 1);

			}
		} else if (serachType == TYPE_UPDATE) {
			OutResult out = (OutResult) apiresult;
			if (out != null && out.getStatus()) {

				if (!mDB.checkEmail(mOutLogin.getProfile().getEmail())) {
					mDB.createProfile(mOutLogin.getProfile());
				} else {
					mDB.updateProfile(mOutLogin.getProfile());
				}
				Intent intent = new Intent(A1002Login.this, A003ListEvent.class);
				startActivityForResult(intent, 1);
			}
		}
	}

	private void forceRegister() {
		Intent i = new Intent(this, A001Register.class);
		this.startActivityForResult(i, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == 0) {
			if (data != null) {
				String email = data.getStringExtra("username");
				String pass = data.getStringExtra("password");
				if (email != null && pass != null) {
					et_username.setText(email);
					et_password.setText(pass);
				}

			}
		} else if (requestCode == 1) {
			et_org.setFocusable(true);
			et_org.setText("");
			et_username.setText("");
			et_password.setText("");
		}
	 if(data != null){
		 String message  = data.getStringExtra("message");
		 if(message !=null) Util.showDialog(this, "CMLite", message);
	 }
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void tokenExpride() {
		// TODO Auto-generated method stub

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_NUMBER:
			CharSequence[] array = { "Red", "Blue", "Yellow" };
			return new AlertDialog.Builder(mContext)
					.setTitle(R.string.select_gender)
					.setSingleChoiceItems(array, -1,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							})
					.setPositiveButton(R.string.update,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							})
					.setNegativeButton(R.string.cancel,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub

								}
							}).create();
		default:
			return null;
		}
	}

	private void getUpdateProfile() {
		if (Util.getNetworkStatus(this)) {
			AsyncTask_Api apiTask = new AsyncTask_Api(this, this, TYPE_UPDATE,
					0, ScreenStopper.STYLE_PROGRESS_PROCESS);
			apiTask.execute();
		} else {
			Util.showDialog(this, R.string.warning,
					R.string.network_not_available, R.drawable.exclamation);
		}
	}

	@Override
	public void onIOnCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIRestart() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIStart() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIResume() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIDestroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onIBackPressed() {
		// TODO Auto-generated method stub

	}
}
